package com.whc.common.design.handle.type;

import cn.hutool.core.util.StrUtil;
import com.whc.common.Constant;
import com.whc.common.design.handle.colmun.ColumnHandle;
import com.whc.vo.GeneralColumn;
import com.whc.vo.Table;

import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.atomic.AtomicBoolean;

/**
 * @author wang-hai-cheng
 * @since 2022/1/1 20:03
 */
public class SaveOrUpdateChain extends TypeChain {

    @Override
    public Object handler(Map<String, Object> body) {
        if (!Constant.OP_TYPE.SAVE_OR_UPDATE.equals(body.get(Constant.VARIABLE_NAME.TYPE))) {
            return handle.handler(body);
        }
        List<Table> saveTables = new ArrayList<>();
        List<Table> updateTables = new ArrayList<>();
        body.forEach((k, v) -> {
            if (v instanceof ArrayList) {
                ((ArrayList<?>) v).forEach(lv -> {
                    Table table = new Table(k, new ArrayList<>());
                    AtomicBoolean isSave = new AtomicBoolean(false);
                    if (lv instanceof LinkedHashMap) {
                        ((LinkedHashMap<String, Object>) lv).forEach((k1, v1) -> {
                            table.getColumns().add(new GeneralColumn(k1, v1));
                            if (k1.equals("id")) {
                                if (v1 instanceof CharSequence) {
                                    if (StrUtil.isBlank((CharSequence) v1)) {
                                        isSave.set(true);
                                    }
                                }
                            }
                        });
                    }
                    if (isSave.get()) {
                        ColumnHandle.handler(table);
                        saveTables.add(table);
                    } else {
                        updateTables.add(table);
                    }
                });
            }
        });
        if (!saveTables.isEmpty()) {
            commonMapper.saveMany(saveTables);
        }
        if (!updateTables.isEmpty()) {
            commonMapper.updateManyById(updateTables);
        }
        return true;
    }
}